package com.taotao.search.service.imp;

import org.apache.solr.client.solrj.SolrQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.search.dao.SearchDao;
import com.taotao.search.pojo.SearchResult;
import com.taotao.search.service.SearchService;

@Service
public class SearchServiceImp implements SearchService {

    @Autowired
    private SearchDao searchDao;

    @Override
    public SearchResult search(String queryString, int page, int rows) throws Exception {
        // 设置查询语句(条件)
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setQuery(queryString);
        // 设置分页
        solrQuery.setStart((page - 1) * rows);
        solrQuery.setRows(rows);
        // 设置默认搜索域
        solrQuery.set("df", "item_keywords");
        // 设置高亮
        solrQuery.setHighlight(true);
        solrQuery.addHighlightField("item_title");
        solrQuery.setHighlightSimplePre("<em style=\"color:red\">");
        solrQuery.setHighlightSimplePost("</em>");
        // 执行查询
        SearchResult searchResult = searchDao.search(solrQuery);
        // 查询总记录数
        long recordCount = searchResult.getRecordCount();
        // 计算总页数
        long pages = getPages(recordCount, rows);
        searchResult.setPageCount(pages);
        //
        searchResult.setCorrentPage(page);
        searchResult.setNumOfPage(rows);
        return searchResult;
    }


    private long getPages(long recordCount, long rows) {
        long pages = recordCount / rows;
        if (recordCount % rows > 0) {
            pages += 1;
        }
        return pages;
    }

}
